package com.asset.dispoal.file.replyDetail.domain.service.command;


import com.alibaba.fastjson2.util.DateUtils;
import com.asset.dispoal.file.replyDetail.domain.db.mapper.FileReplyDetailMapper;
import com.asset.dispoal.file.replyDetail.domain.dto.ReplyDetailExportTemplate;
import com.asset.dispoal.file.replyDetail.dto.FileReplyRequest;
import com.asset.dispoal.file.replyDetail.dto.FileReplyUserRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.spring.util.DataUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @author qr
 * @date 2021/11/24$
 */
@Component
@Slf4j
public class FileReplyDetailExcelDataSaveCommand implements BaseCommand<Map<String, Object>, Result> {

    @Autowired
    private BaseIdeable<String> idWorker;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    static String regex = "(\\d{4}-\\d{1,2}-\\d{1,2})([\\u4e00-\\u9fa5]*)";

    @SneakyThrows
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(Map<String, Object> map) {
        List<ReplyDetailExportTemplate> bsDataDetailExportTemplateList = (List<ReplyDetailExportTemplate>) map.get("dataList");
        if (CollectionUtil.isEmpty(bsDataDetailExportTemplateList)) {
            return Result.faild("导入数据为空");
        }
        SqlSession sqlSession = this.sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        FileReplyDetailMapper mapper = this.sqlSessionTemplate.getMapper(FileReplyDetailMapper.class);

        FileReplyRequest lastData = null;
        for (ReplyDetailExportTemplate data : bsDataDetailExportTemplateList) {
            FileReplyRequest request = DataUtil.copyTo(data, FileReplyRequest.class);
            if (request != null) {
                if (lastData != null && StringUtil.equals(request.getChannel(), lastData.getChannel()) &&
                        request.getReplyAmount().equals(lastData.getReplyAmount()) &&
                        request.getReplyDate().equals(lastData.getReplyDate()) &&
                        StringUtil.equals(request.getCollectBankno(), lastData.getCollectBankno()) &&
                        StringUtil.equals(request.getBatchName(), lastData.getBatchName())
                ) {
                    mapper.saveUser(idWorker.generateId(), request.getId(), data.getName(), data.getIdcard());
                }
            }

            request.setId(idWorker.generateId());
            if (data.getName() != null || data.getIdcard() != null) {
                FileReplyUserRequest userRequest = new FileReplyUserRequest();
                userRequest.setId(idWorker.generateId());
                userRequest.setName(data.getName());
                userRequest.setIdcard(data.getIdcard());
                request.setUserList(Stream.of(userRequest).collect(Collectors.toList()));
            }
            //代收代付
            String collectContent = data.getCollectContent();
            //律所分成
            String divideContent = data.getDivideContent();
            if (StringUtil.isNotEmpty(collectContent)) {
                String[] collectArr = getDataConvertArr(collectContent);
                if (ObjectUtil.isNotEmpty(collectArr)) {
                    request.setCollectReviewDate(DateUtils.parseDate(collectArr[0]));
                    request.setCollectReviewName(collectArr[1]);
                }
            }
            if (StringUtil.isNotEmpty(divideContent)) {
                String[] divideArr = getDataConvertArr(divideContent);
                if (ObjectUtil.isNotEmpty(divideArr)) {
                    request.setDivideReviewDate(DateUtils.parseDate(divideArr[0]));
                    request.setDivideReviewName(divideArr[1]);
                }
            }
            lastData = request;
            mapper.save(request);
        }

        sqlSession.flushStatements();
        sqlSession.commit();
        sqlSession.clearCache();
        sqlSession.close();
        return Result.ok();
    }

    private static String[] getDataConvertArr(String input) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            // 捕获组1是日期，捕获组2是汉字
            String date = matcher.group(1);
            String chineseText = matcher.group(2);
            return new String[]{date, chineseText};
        }
        return null;
    }
}